﻿//
// Copyright 2024 Exhunter Technology Co.Ltd2.
//

using System;
using X18.Framework.Core.Security.Sm;

namespace X18.Framework.Core.Security.Encryptor
{
    /// <summary>
    /// SM2加密算法
    /// </summary>
    public class Sm2Encryptor : IDataEncryptor
    {
        /// <summary>
        /// 默认公钥
        /// </summary>
        private static readonly string DefalutPublicKey = "BKr1QMI/KjN4JVd8aQSdjanGOMg1DsBMG7d8DRK0DcDcX1B8ilj20bZvz3FL+k3kTtO1dxHuq9d3VrmJGJNLxrw=";
        /// <summary>
        /// 默认公钥（字节类型）
        /// </summary>
        private static readonly byte[] DefalutPublicByteKey;
        /// <summary>
        /// 默认私钥
        /// </summary>
        private static readonly string DefalutPrivateKey = "Xjv2db4POVCuRbIzd/5odABWjuZPxRpCocXAe4fIXhs=";
        /// <summary>
        /// 默认私钥（字节类型）
        /// </summary>
        private static readonly byte[] DefalutPrivateByteKey;

        static Sm2Encryptor()
        {
            DefalutPublicByteKey = Convert.FromBase64String(DefalutPublicKey);
            DefalutPrivateByteKey = Convert.FromBase64String(DefalutPrivateKey);
        }

        public static KeyPair GetKeyPair()
        {
            return Sm2.GetKeyPair();
        }

        public static byte[] Encrypt(byte[] plainBytes, byte[] key = null)
        {
            byte[] key0 = key ?? DefalutPublicByteKey;
            byte[] result = Sm2.Encrypt(key0, plainBytes);
            return result;
        }

        public static byte[] Decrypt(byte[] cipherBytes, byte[] key = null)
        {
            byte[] key0 = key ?? DefalutPrivateByteKey;
            byte[] result = Sm2.Decrypt(key0, cipherBytes);
            return result;
        }

        public static byte[] Sign(byte[] privateKey, byte[] data)
        {
            return Sm2.Sign(privateKey, data);
        }

        public static bool VerifySign(byte[] publicKey, byte[] data, byte[] sign)
        {
            return Sm2.VerifySign(publicKey, data, sign);
        }

        public override byte[] EncryptToBytes(byte[] plainBytes, byte[] key = null)
        {
            return Encrypt(plainBytes, key);
        }

        public override byte[] DecryptFromBytes(byte[] cipherBytes, byte[] key = null)
        {
            return Decrypt(cipherBytes, key);
        }

        public override string GenerateKey()
        {
            KeyPair key = GetKeyPair();
            var publicBase64 = Convert.ToBase64String(key.PublicKey);
            var privateBase64 = Convert.ToBase64String(key.PrivateKey);
            var result = string.Format("{0};{1}", publicBase64, privateBase64);
            return result;
        }
    }
}
